package news.servlet;

import news.dao.NewsDao;
import news.pojo.News;
import news.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/news-manage")
public class NewsManageServlet extends BaseServlet {
    private NewsDao newsDao = new NewsDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int page = getIntegerParam("page", 1);// 当前是第几页
        int size = getIntegerParam("size", 15); // 每页的条数
        // 判断 session是否有登录后的凭证
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("login_user");
        if (u == null) {
//            // 说明没有login凭证
//            resp.sendRedirect("/login");
//            return;
        }
        req.setAttribute("user", u);
        // 查询新闻内容
        List<News> newsList = new ArrayList<>();
        // 总页码
        int totalPage = 0;
        // 搜索关键字
        String title = req.getParameter("title");
        try {
            newsList = newsDao.selectByPage(page, size,title); // 默认查询所有
            long count = newsDao.selectCount(title);// 获取到总的条数
            totalPage = (int) Math.ceil(count * 1.0 / size);//计算的到总页码
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 开始计算应该显示的页码
        int showPageCount = 9; // 显示的页码数量
        int startPage = 1; // 起始页码
        int endPage = totalPage; // 结束页码
        int prevPage = 1;//上一页
        int nextPage = totalPage;//下一页
        // 只有总页码数超过了要显示的页码数量才进行判断
        if (totalPage > showPageCount) {
            int halfPageCount = (showPageCount - 1) / 2; // 当前页的左右两侧分别显示的页码数量
            startPage = page - halfPageCount;// 假设当前页为5 -> 5 -4 = 1
            endPage = page + halfPageCount; // 5 + 4 => 9
            // 起始页小于1的情况
            if (startPage <= 0) {
                startPage = 1;
                endPage = startPage + showPageCount - 1;
            }
            // 结束页不能大于最大页码
            if (endPage > totalPage) {
                endPage = totalPage;
                startPage = totalPage - showPageCount + 1;
            }
        }
        if (page > 1) prevPage = page - 1;
        if (page < totalPage) nextPage = page + 1;

        req.setAttribute("newsList", newsList);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("title",title);
        req.setAttribute("startPage", startPage);
        req.setAttribute("endPage", endPage);
        req.setAttribute("prevPage", prevPage);
        req.setAttribute("nextPage", nextPage);
        // 显示新闻管理页
        showPage("manage");
    }
}
